package com.jiangxun.leetcode.editor.cn;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//leetcode submit region begin(Prohibit modification and deletion)
class Solution40 {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(candidates); // 排序候选数组
        backtrack(candidates, target, new ArrayList<>(), 0, 0, result);
        return result;
    }

    private void backtrack(int[] candidates, int target, List<Integer> path, int currentSum, int startIndex, List<List<Integer>> result) {
        if (currentSum == target) {
            result.add(new ArrayList<>(path));
            return;
        }

        if (currentSum > target) {
            return;
        }

        for (int i = startIndex; i < candidates.length; i++) {
            // 跳过重复的候选数
            if (i > startIndex && candidates[i] == candidates[i - 1]) {
                continue;
            }
            path.add(candidates[i]);
            backtrack(candidates, target, path, currentSum + candidates[i], i + 1, result);
            path.remove(path.size() - 1);
        }
    }
}
//leetcode submit region end(Prohibit modification and deletion)
